<?php

namespace app\common\model;

use helper\Tree;

class DictClassModel extends BaseModel
{

  protected $table = 'dict_class';

  /**
   * 分类列表
   * @return array
   * @throws \Exception
   */
  public function getList()
  {
    $list = $this->order('show_order asc')->select()->toArray();
    $treeList = Tree::tree($list, 'name'); //转换树型
    return array_values($treeList);
  }

  /**
   * 添加
   * @param $data
   * @return DictClassModel|\think\Model
   * @throws \Exception
   */
  public function add($data)
  {
    if ($this->where('code', $data['code'])->find()) abort(500, '该编码已存在');
    return self::create($data);
  }

  /**
   * 编辑
   * @param $data
   * @return DictClassModel|\think\Model
   * @throws \Exception
   */
  public function edit($data)
  {
    $info = $this->where('id', $data['id'])->find();
    if ($info['code'] != $data['code']) {
      if ($this->where('code', $data['code'])->find()) abort(500, '该编码已存在');
      //同步修改字典编码
      DictModel::where('class_code',$info['code'])->update([
          'class_code'=>$data['code']
      ]);
    }
    return self::update($data);
  }

  /**
   * 删除
   * @param $id
   * @return bool
   * @throws \Exception
   */
  public function del($id)
  {
    $info = $this->where('id', $id)->find();
    if ($this->where('pid', $id)->find()) abort(500, '存在下级分类，不允许删除');
    if (DictModel::where('class_code', $info['code'])->find()) abort(500, '存在对应字典，不允许删除');
    return $this->where('id', $id)->delete();
  }
}
